package com.efivestar.idm.api.service;

import com.efivestar.idm.api.common.ResultDto;
import com.efivestar.idm.api.domain.TianyiUserDomain;
import com.efivestar.idm.api.repository.TianyiUserMapper;
import com.efivestar.idm.api.util.tianyi.Device;
import com.efivestar.idm.api.util.tianyi.MobileServicesPortType;
import com.efivestar.idm.api.util.tianyi.UserLoginReq;
import com.efivestar.idm.api.util.tianyi.UserLoginRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class TianyiUserService {

    Logger logger = LoggerFactory.getLogger(TianyiUserService.class);


    @Autowired
    private TianyiUserMapper tianyiUserMapper;

    @Autowired
    private MobileServicesPortType mobileServicesPortType;


    /**
     * 当登录成功的情况下，则返回登录的session.
     * 登录失败，则返回 null.
     *
     * @param account
     * @param password
     * @param cameraId
     * @return
     */
    @Transactional
    public ResultDto login(String account, String password, String cameraId) {
        try {
            UserLoginReq userLoginReq = new UserLoginReq();
            userLoginReq.setAccount(account);
            userLoginReq.setPassword(password);
            UserLoginRes userLoginRes = mobileServicesPortType.userLogin(userLoginReq);
            int result = userLoginRes.getResult();
            // 登录成功
            if (result == 0) {
                String loginSession = userLoginRes.getLoginSession();
                TianyiUserDomain tianyiUserDomain = TianyiUserDomain.builder().account(account)
                        .password(password)
                        .session(loginSession)
                        .updateTime(new Date()).build();
                List<Device> devices = userLoginRes.getDeviceAll().getDevice();
                // 在智能锁平台已经绑定了摄像头的情况下， 判断当前用户在天翼平台是否也绑定了
                if (devices == null || devices.isEmpty() || !devices.stream().anyMatch(d -> d.getDevID().equals(cameraId))) {
                    logger.error("天翼摄像头：{} 在用户：{} 下未绑定", cameraId, account);
                    ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
                    exceptionObj.setCode("tianyi.unExistDevice");
                    return ResultDto.builder().success("false").data(exceptionObj).build();
                }
                tianyiUserMapper.replaceTianyiUser(tianyiUserDomain);
                return ResultDto.builder().data(loginSession).build();
            } else if (1 == userLoginRes.getResult()) {
                logger.error("天翼摄像头：{} 用户：{} 在天翼平台不存在", cameraId, account);
                ResultDto.ResultDtoBuilder<Object> builder = ResultDto.builder();
                // 用户不存在
                ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
                // 账户在天翼平台不存在
                exceptionObj.setCode("tianyi.invalid_account");
                builder.success("false").exceptionObj(exceptionObj);
                return builder.build();
            } else if (2 == userLoginRes.getResult()) {
                logger.error("天翼摄像头：{} 用户：{} 密码不正确", cameraId, account);
                // 密码不正确
                ResultDto.ResultDtoBuilder<Object> builder = ResultDto.builder();
                ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
                exceptionObj.setCode("tianyi.invalid_password");
                builder.success("false").exceptionObj(exceptionObj);
                return builder.build();
            } else if (5 == userLoginRes.getResult()) {
                logger.error("天翼摄像头：{} 用户：{} 密码失败次数过多", cameraId, account);
                // 密码尝试次数过多
                ResultDto.ResultDtoBuilder<Object> builder = ResultDto.builder();
                ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
                exceptionObj.setCode("tianyi.login_error_too_many_times");
                builder.success("false").exceptionObj(exceptionObj);
                return builder.build();
            } else if (6 == userLoginRes.getResult()) {
                logger.error("天翼摄像头：{} 用户：{} 密码太简单", cameraId, account);
                // 密码太简单
                ResultDto.ResultDtoBuilder<Object> builder = ResultDto.builder();
                ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
                exceptionObj.setCode("tianyi.password_too_simple");
                builder.success("false").exceptionObj(exceptionObj);
                return builder.build();
            } else {
                logger.error("天翼摄像头：{} 用户：{} 内部服务错误", cameraId, account);
                ResultDto.ResultDtoBuilder<Object> builder = ResultDto.builder();
                ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
                exceptionObj.setCode("tianyi.server_error");
                builder.success("false").exceptionObj(exceptionObj);
                return builder.build();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            ResultDto.ExceptionObj exceptionObj = new ResultDto.ExceptionObj();
            exceptionObj.setCode("tianyi.server_error");
            logger.error("天翼服务器异常：{}", ex);
            return ResultDto.builder().success("false").exceptionObj(exceptionObj).build();
        }
    }

}



